package models

import (
	"fmt"
	"rongyy/src/app"
	"rongyy/src/middlewares"
)

type IpReserveModel struct {
	BaseModel    `xorm:"extends"`
	PatientId    string `json:"patient_id"`
	InpatientNo  string `json:"inpatient_no"`
	Status       string `json:"status"`
	Openid       string `json:"openid"`
	RejectReason string `json:"reject_reason"`
	OperatorCode string `json:"operator_code"`
}

type ReqIpsHandelModel struct {
	Id           int64  `json:"id"`
	OperatorCode string `json:"operator_code"`
	Reason       string `json:"reason"`
}

type ReqIpReserveQuery struct {
	PatientId string `json:"patient_id"`
	Limit     int    `json:"limit"`
	Offset    int    `json:"offset"`
	Status    string `json:"status"`
}

func (irm *IpReserveModel) TableName() string {
	return "ip_reserve"
}

func (irm *IpReserveModel) Insert() error {
	_, err := app.DB().Insert(irm)
	if err != nil {
		middlewares.Logger.Println("DEBUG - WxUser Insert failed ", err)
		return err
	}
	return nil
}

func (rm *IpReserveModel) Update() error {
	_, err := app.DB().Table("ip_reserve").ID(rm.Id).Cols("status", "reject_reason", "operator_code").Update(rm)
	if err != nil {
		return err
	}
	return err
}

func (rm *IpReserveModel) Query(req *ReqIpReserveQuery) ([]IpReserveModel, int64, error) {
	pres := make([]IpReserveModel, 0)
	s := app.DB().Table("ip_reserve")
	if req.PatientId != "" {
		pid := fmt.Sprintf("%%%s%%", req.PatientId)
		s = s.Where("patient_id like ?", pid)
	}

	if req.Status != "" {
		status := fmt.Sprintf("%%%s%%", req.Status)
		s = s.Where("status like ?", status)
	}
	total, err := s.Limit(req.Limit, req.Offset).Desc("created_at").FindAndCount(&pres)
	if err != nil {
		return nil, 0, err
	}
	return pres, total, err
}
